package com.artemis.event;

import com.artemis.utils.Bag;

/**
 * A basic implementation of the {@link EventDeliverySystem}.
 * If want to pool your SystemEvents, you can alse use the {@link PooledEventDeliverySystem}.
 * 
 * @author kryo
 *
 */
public class BasicEventDeliverySystem implements EventDeliverySystem {
	protected Bag<Bag<SystemEvent>> eventQueues;
	
	public BasicEventDeliverySystem() {
		eventQueues = new Bag<Bag<SystemEvent>>();
	}
	
	@Override
	public void initialize() {
	}

	@Override
	public void update() {
		for(int i = 0; i < eventQueues.getCapacity(); i++) {
			Bag<SystemEvent> queue = eventQueues.get(i);
			if(queue != null) {
				queue.clear();
			}
		}
	}

	@Override
	public void postEvent(SystemEvent e) {
		if(e == null) return;
		int typeId = e.getTypeId();
		if(!eventQueues.isIndexWithinBounds(typeId)) {
			eventQueues.ensureCapacity(typeId);
		}
		Bag<SystemEvent> queue = eventQueues.get(typeId);
		if(queue == null) {
			queue = new Bag<SystemEvent>(16);
			eventQueues.set(typeId, queue);
		}
		e.handled = false;
		queue.add(e);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <E extends SystemEvent> void getEvents(int typeId, Bag<E> events) {
		if(events.isIndexWithinBounds(typeId)) {
			Bag<SystemEvent> queue = eventQueues.get(typeId);
			if(queue != null) {
				for(int i = 0; i < queue.size(); i++) {
					SystemEvent e = queue.get(i);
					if(!e.handled) events.add((E) e);
				}
			}
		}
	}

}
